﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.Collections.ObjectModel;
using System.Windows.Browser;
using System.Xml.Linq;

namespace CoverFlowClient.Pages
{
    public partial class ImageCoverFlow : Page
    {
        ObservableCollection<MovieTrailer> trailers;
        public ImageCoverFlow()
        {
            InitializeComponent();

            trailers = new ObservableCollection<MovieTrailer>();
            flowControl.ItemsSource = trailers;
            
            Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            WebClient webClient = new WebClient();
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
            Uri xmlUri = new Uri(HtmlPage.Document.DocumentUri, "GetTrailersXml.ashx");
            webClient.DownloadStringAsync(xmlUri);
        }
        void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("There was an error retrieving xml");
                return;
            }
            XDocument xDoc = XDocument.Parse(e.Result);
            foreach (XElement xMovieInfo in xDoc.Descendants("movieinfo"))
            {
                try
                {
                    MovieTrailer trailer = new MovieTrailer(xMovieInfo);
                    trailers.Add(trailer);
                }
                catch { }
            }
            flowControl.SelectedIndex = 0;
            flowControl.Focus();
        }
    }
}
